﻿using AutoMapper;
using InitQ.Cache;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using SkiaSharp;
using Smart.Admin.Domain.Common;
using Smart.Admin.Domain.Model.Config;
using Smart.Admin.Domain.Model.Const;
using Smart.Admin.Domain.Model.Entity;
using Smart.Admin.Domain.Model.Enum;
using Smart.Admin.Domain.Model.Request.Account;
using Smart.Admin.Domain.Model.Request.Notice;
using Smart.Admin.Domain.Model.Response;
using Smart.Admin.Domain.Model.Response.Account;
using Smart.Admin.Domain.Model.Response.Notice;
using Smart.Admin.Domain.Model.Response.Menu;
using Smart.Admin.Domain.Repository;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Smart.Admin.Domain.Model.Request.Employee;
using Smart.Admin.Domain.Model.Response.Employee;

namespace Smart.Admin.Domain.Service
{
    /// <summary>
    /// 通知服务
    /// </summary>
    public class NoticeService: EmployeeExtensions
    {
        private readonly SmartAdminDbContext _context;
        private readonly ICacheService _redisService;
        private readonly IOptions<JwtOptions> _options;
        private readonly IMapper _mapper;
        public NoticeService(SmartAdminDbContext context, ICacheService redisService, IOptions<JwtOptions> options, IMapper mapper)
        {
            _context = context;
            _redisService = redisService;
            _options = options;
            _mapper = mapper;
        }



        /// <summary>
        /// 分页查询通知列表
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResponse<List<GetNoticeResponse>>> GetNoticePageList(GetNoticePageListRequest request)
        {
            var response = new JsonResponse<List<GetNoticeResponse>>();
            try
            {
                var query = from notice in _context.Notice
                            join employee in _context.Employee on notice.CreateUserId equals employee.Id
                            where notice.IsDelete == false
                            select new GetNoticeResponse ()
                            {
                                ScheduledPublishFlag=notice.ScheduledPublishFlag,
                                Author=notice.Author,
                                ContentHtml=notice.ContentHtml,
                                ContentText=notice.ContentText,
                                CreateTime=notice.CreateTime,
                                CreateUserId=notice.CreateUserId,
                                DocumentNumber=notice.DocumentNumber,
                                CreateUserName=employee==null?"":employee.Name,
                                IsDelete=notice.IsDelete,
                                NoticeId=notice.Id,
                                NoticeType=notice.NoticeType,
                                PageViewCount=notice.PageViewCount,
                                PublishTime=notice.PublishTime,
                                Source=notice.Source,
                                Title=notice.Title,
                                UpdateTime=notice.UpdateTime,
                                UserViewCount=notice.UserViewCount
                            };

                query = query.WhereIf(request.NoticeType.HasValue, p => p.NoticeType == request.NoticeType);

                query = query.WhereIf(request.StartCreateTime.HasValue, p => p.CreateTime >= request.StartCreateTime);
                query = query.WhereIf(request.EndCreateTime.HasValue, p => p.CreateTime <= request.EndCreateTime);

                query = query.WhereIf(request.StartPublishTime.HasValue, p => p.PublishTime >= request.StartPublishTime);
                query = query.WhereIf(request.EndPublishTime.HasValue, p => p.PublishTime <= request.EndPublishTime);

                query = query.WhereIf(!string.IsNullOrEmpty(request.Keyword), p => p.Title.Contains(request.Keyword) || p.Author.Contains(request.Keyword) || p.Source.Contains(request.Keyword));
                query = query.Distinct();
                var data = await query.OrderByDescending(m => m.CreateTime).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToListAsync();


                response.code = "0";
                response.data = _mapper.Map<List<GetNoticeResponse>>(data);
                response.total = await query.CountAsync();
                return response;
            }
            catch (Exception ex)
            {
                return JsonResult.Error<List<GetNoticeResponse>>(message: "系统错误");
            }
        }


        /// <summary>
        /// 查询通知信息
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResponse<GetNoticeResponse>> GetNoticeInfo(long noticeId)
        {
            var response = new JsonResponse<GetNoticeResponse>();
            try
            {
                var model = await _context.Notice.AsNoTracking().Where(m=>m.IsDelete==false).FirstOrDefaultAsync(m=>m.Id == noticeId);
                if(model == null) return JsonResult.Error<GetNoticeResponse>(message: "数据不存在");
                response.code = "0";
                response.data = _mapper.Map<GetNoticeResponse>(model);
                return response;
            }
            catch (Exception ex)
            {
                return JsonResult.Error<GetNoticeResponse>(message: "系统错误");
            }
        }

        /// <summary>
        /// 创建通知
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<JsonResponse> CreateNotice(CreateNoticeRequest request) 
        {
            try
            {
                if(request ==null) return JsonResult.Error(message: "参数错误");
                var bl = await _context.Notice.AnyAsync(m => m.Title == request.Title);
                if (bl) return JsonResult.Error(message:"通知标题已存在");
                var model = _mapper.Map<NoticeEntity>(request);
                model.CreateUserId = Convert.ToInt64(EmployeeId);
                model.CreateTime = DateTime.Now;
                model.UpdateTime = model.CreateTime;
                await _context.Notice.AddAsync(model);
                await _context.SaveChangesAsync();
                return JsonResult.Success();
            }
            catch (Exception ex)
            {
                return JsonResult.Error(message: "系统错误");
            }
        }


        /// <summary>
        /// 修改通知
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<JsonResponse> UpdateNotice(UpdateNoticeRequest request)
        {
            try
            {
                if (request == null) return JsonResult.Error(message: "参数错误");
                var model = await _context.Notice.Where(m=>m.IsDelete == false).FirstOrDefaultAsync(m => m.Id == request.NoticeId);
                if (model == null) return JsonResult.Error(message:"数据不存在");
                var bl = await _context.Notice.Where(m => m.IsDelete == false).AnyAsync(m => m.Title == request.Title && m.Id != request.NoticeId);
                if (bl) return JsonResult.Error(message:"通知标题已存在");

                model.ScheduledPublishFlag=request.ScheduledPublishFlag;
                model.Author=request.Author;
                model.ContentHtml=request.ContentHtml;
                model.ContentText=request.ContentText;
                model.DocumentNumber=request.DocumentNumber;
                model.NoticeType=request.NoticeType;
                model.PageViewCount=request.PageViewCount;
                model.PublishTime=request.PublishTime;
                model.Source=request.Source;
                model.Title=request.Title;
                model.UserViewCount =request.UserViewCount;
                model.UpdateTime = DateTime.Now;

                _context.Notice.Update(model);
                await _context.SaveChangesAsync();
                return JsonResult.Success();
            }
            catch (Exception ex)
            {
                return JsonResult.Error(message: "系统错误");
            }
        }

        /// <summary>
        /// 删除通知
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<JsonResponse> DeleteNotice(DeleteNoticeRequest request)
        {
            try
            {
                if(request == null || request.NoticeIdList == null || request.NoticeIdList.Count == 0) return JsonResult.Error(message: "参数错误");
                var list = await _context.Notice.Where(m => request.NoticeIdList.Contains(m.Id)).ToListAsync();
                if (list.Count > 0)
                {
                    foreach (var item in list)
                    {
                        item.IsDelete = true;
                    }
                    _context.Notice.UpdateRange(list);
                    await _context.SaveChangesAsync();
                }
                return JsonResult.Success();
            }
            catch (Exception ex)
            {
                return JsonResult.Error(message: "系统错误");
            }
        }

    }
}
